
#include <stdio.h>
#include "SDL.h"


char *lastErr = NULL;
Uint8 *audioBuf = NULL;
Uint32 audioLen = 0;


void mixAudio(void *unused, Uint8 *stream, int len)
{
    int amount;

	if (audioLen<=0 || len<=0)
		return;

    if (audioLen > (Uint32)len)
        amount = len;
	else
		amount = (int)audioLen;

    SDL_MixAudio(stream, audioBuf, amount, SDL_MIX_MAXVOLUME);
    audioBuf += amount;
	audioLen -= amount;
}


int playAudio(char *name)
{
	SDL_AudioSpec wave;

	if (SDL_LoadWAV("res/1.wav", &wave, &audioBuf, &audioLen) == NULL)
	{
		lastErr = SDL_GetError();
		return 1;
	}

    wave.callback = mixAudio;
    wave.userdata = NULL;

	SDL_OpenAudio(&wave, NULL);
	SDL_PauseAudio(0);

	return 0;
}


void stopAudio()
{
	SDL_CloseAudio();
}


int main(int argc, char *argv[])
{
	SDL_Surface *surface;
	SDL_Surface *mask;
	SDL_Event event;
	int ret;

	ret = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER);
	if (ret < 0)
	{
		lastErr = SDL_GetError();
		return 1;
	}

	surface = SDL_SetVideoMode(320, 240, 32, SDL_HWSURFACE|SDL_DOUBLEBUF);
	if (surface == NULL)
	{
		lastErr = SDL_GetError();
		return 2;
	}

	SDL_WM_SetCaption("SDL demo", "res/1.ico");

	bool loop = true;
	while (loop)
	{
		if (SDL_PollEvent(&event) > 0)
		{
			if (event.type == SDL_QUIT)
			{
				loop = false;
			}
			else if (event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_SPACE)
			{
				playAudio("res/1.wav");
				SDL_Delay(1000);
			}
		}

		ret = SDL_LockSurface(surface);
		if (ret != 0)
		{
			lastErr = SDL_GetError();
			break;
		}

        for (int i=0; i<320; i++)
        {
            for (int j=0; j<240; j++)
            {
				Uint32 val = SDL_MapRGB(surface->format, j/2, j/2, i/3);
				((Uint32 *)surface->pixels)[j*320+i] = val;
            }
        }

		SDL_UnlockSurface(surface);


		SDL_Rect dect;
		char name[128];
		sprintf(name, "res/%d.bmp", SDL_GetTicks()/5000%4);

		mask = SDL_LoadBMP(name);

        dect.x = 136;
        dect.y = 96;
        ret = SDL_BlitSurface(mask, NULL, surface, &dect);
		if (ret != 0)
		{
			lastErr = SDL_GetError();
			break;
		}

		SDL_FreeSurface(mask);

		SDL_Flip(surface);
	}

	stopAudio();
	SDL_Quit();
	return 0;
}

